package com.uyayo.system.config.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uyayo.framework.common.exception.CodeMultipleException;
import com.uyayo.framework.common.exception.RecordNotExistException;
import com.uyayo.framework.common.util.FileUpload;
import com.uyayo.framework.common.util.FtpUtil;
import com.uyayo.framework.common.util.PathUtil;
import com.uyayo.framework.common.util.io.FileUtil;
import com.uyayo.framework.pagehelper.pojo.OrderBy;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.util.OrderByUtil;
import com.uyayo.system.config.dto.SysFileDTO;
import com.uyayo.system.config.entity.SysFile;
import com.uyayo.system.config.entity.SysServer;
import com.uyayo.system.config.mapper.SysFileMapper;
import com.uyayo.system.config.model.SysFileCondition;
import com.uyayo.system.config.service.SysFileService;
import com.uyayo.system.config.service.SysServerService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("sysFileService")
public class SysFileServiceImpl implements SysFileService {

	@Resource
	private SysFileMapper sysFileMapper;

	@Resource
	private SysServerService sysServerService;

	@Override
	public SysFile getFilesById(long id){
		return sysFileMapper.selectByPrimaryKey(id);
	}

	@Override
	public PageBean<SysFile> selectFileByPage(Integer pageCurrent, Integer pageSize,String sort,String order,SysFileCondition sysFileCondition) {

		List<SysFile> sysFiles;
		//分页处理
		List<OrderBy> orderBys = new ArrayList<>();
		orderBys.add(new OrderBy("type", "type"));
		orderBys.add(new OrderBy("description", "description"));
		orderBys.add(new OrderBy("createTime", "create_time"));
		orderBys.add(new OrderBy("updateTime", "update_time"));
		orderBys.add(new OrderBy("remark", "remark"));
		OrderByUtil orderByUtil = new OrderByUtil();
		String orderBy = orderByUtil.getOrderBy(orderBys, sort, order);
		PageHelper.startPage(pageCurrent, pageSize);
		Example example = new Example(SysFile.class);
		if(!StringUtils.isEmpty(orderBy)){
			example.setOrderByClause(orderBy);
		}
		Example.Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(sysFileCondition.getName())){
			criteria.andLike("name","%"+sysFileCondition.getName()+"%");
		}
		if(!StringUtils.isEmpty(sysFileCondition.getTitle())){
			criteria.andLike("title","%"+sysFileCondition.getTitle()+"%");
		}
		if(sysFileCondition.getBeginCreatedTime()!=null || sysFileCondition.getEndCreatedTime()!=null){
			criteria.andBetween("createTime", sysFileCondition.getBeginCreatedTime(), sysFileCondition.getEndCreatedTime());
		}
		sysFiles = sysFileMapper.selectByExample(example);

		//取记录总条数
		PageInfo<SysFile> pageInfo = new PageInfo<>(sysFiles);

		return new PageBean<>(pageInfo.getTotal(), pageCurrent, pageSize, sysFiles);
	}

	@Override
	public SysFileDTO createFile(SysFile sysFile,String filePath,String fileName, InputStream inputStream) throws CodeMultipleException, IOException {
		SysFileDTO sysFileDTO = new SysFileDTO();
		SysFile sysFileTest = getFileByCode(sysFile.getCode());
		if(sysFileTest!=null){
			throw new CodeMultipleException("Code multiple error!");
		}

		SysServer sysServer = new SysServer();
		sysServer.setType(1);
		sysServer.setStatus(1);
		sysServer = sysServerService.selectSysServer(sysServer).get(0);
		String uploadBaseUrl = sysServer.getUrl();
		String default_upload_path = sysServer.getUploadDirectory();
		String urlUpload = default_upload_path+filePath+ "/" + fileName;
		//String url = uploadBaseUrl+urlUpload;
		sysFile.setUrl(urlUpload);
		sysFile.setName(fileName);
		sysFile.setUploadWay(2);
		sysFile.setServerId(sysServer.getId());
		int count = sysFileMapper.insertSelective(sysFile);
		if(count>0){
			SysServer sysServerWeb = new SysServer();
			sysServerWeb.setType(0);
			sysServerWeb.setStatus(1);
			sysServerWeb = sysServerService.selectSysServer(sysServerWeb).get(0);
			String uploadBaseUrlWeb = sysServerWeb.getUrl();

			if(sysServer.getType()==1){
				String ftpHost = sysServer.getHost();
				int ftpPort = sysServer.getPort();
				String ftpUsername = sysServer.getUsername();
				String ftpPassword = sysServer.getPassword();
				boolean uploadStatus = FtpUtil.uploadFile(ftpHost,ftpPort,ftpUsername,ftpPassword,default_upload_path,filePath,fileName,inputStream);
				if(uploadStatus){
					sysFileDTO.setUrl(urlUpload);
					sysFileDTO.setUrlFull(uploadBaseUrlWeb+urlUpload);
					return sysFileDTO;
				}else{
					sysFileMapper.deleteByPrimaryKey(sysFile.getId());
				}
			}else{
				String realPath = PathUtil.getRootClassPath()+default_upload_path+filePath;
				FileUpload.copyFile(inputStream,realPath, fileName);
				sysFileDTO.setUrl(urlUpload);
				sysFileDTO.setUrlFull(uploadBaseUrlWeb+urlUpload);
				return sysFileDTO;			}
		}
		return  null;
	}

	@Override
	public boolean updateFile(SysFile sysFile, String filePath,String fileName, InputStream inputStream) throws CodeMultipleException, RecordNotExistException, IOException {
		SysFile sysFileOld = sysFileMapper.selectByPrimaryKey(sysFile.getId());
		if(sysFileOld==null) {
			throw new RecordNotExistException("Record not exist exception!");
		}
		SysFile sysFileTest = getFileByCode(sysFile.getCode());
		if(sysFileTest!=null && !Objects.equals(sysFile.getId(), sysFileTest.getId())){
			throw new CodeMultipleException("Code multiple error!");
		}
		SysServer sysServer = sysServerService.getSysServerByEnabled();
		String ftpHost = sysServer.getHost();
		int ftpPort = sysServer.getPort();
		String ftpUsername = sysServer.getUsername();
		String ftpPassword = sysServer.getPassword();
		String uploadBaseUrl = sysServer.getUrl();
		String default_upload_path = sysServer.getUploadDirectory();
		String url = uploadBaseUrl+default_upload_path+filePath+ "/" + fileName;
		sysFile.setUrl(url);
		sysFile.setName(fileName);
		sysFile.setUploadWay(2);
		sysFile.setServerId(sysServer.getId());
		int count = sysFileMapper.updateByPrimaryKeySelective(sysFile);
		if(count>0){
			if(sysServer.getType()==1){
				boolean uploadStatus = FtpUtil.uploadFile(ftpHost,ftpPort,ftpUsername,ftpPassword,default_upload_path,filePath,fileName,inputStream);
				if(uploadStatus){
					FtpUtil.deleteFile(ftpHost, ftpPort, ftpUsername, ftpPassword, sysFileOld.getUrl());
					return true;
				}else{
					sysFileMapper.deleteByPrimaryKey(sysFile.getId());
				}
			}else{
				String realPath = PathUtil.getRootClassPath()+default_upload_path+filePath;
				FileUpload.copyFile(inputStream, realPath, fileName);
				realPath = PathUtil.getRootClassPath() + sysFileOld.getUrl();
				if (!StringUtils.isEmpty(realPath)) {
					FileUtil.deleteFile(realPath);
				}
			}
		}
		return  false;
	}

	@Override
	public boolean deleteFile(long fileId) throws RecordNotExistException {
		SysFile sysFile = sysFileMapper.selectByPrimaryKey(fileId);
		if(sysFile==null) {
			throw new RecordNotExistException("Record not exist exception!");
		}
		SysServer sysServer = sysServerService.getSysServerById(sysFile.getServerId());
		String url = sysFile.getUrl();
		String url_ = url.substring(url.lastIndexOf(sysServer.getUploadDirectory()),url.length());
		int deleteCount = sysFileMapper.deleteByPrimaryKey(fileId);
		if(deleteCount>0) {
			if(sysServer.getType()==1) {
				String ftpHost = sysServer.getHost();
				int ftpPort = sysServer.getPort();
				String ftpUsername = sysServer.getUsername();
				String ftpPassword = sysServer.getPassword();
				FtpUtil.deleteFile(ftpHost, ftpPort, ftpUsername, ftpPassword, url_);
			}else{
				String realPath = PathUtil.getRootClassPath()+url_;
				if (!StringUtils.isEmpty(realPath)) {
					FileUtil.deleteFile(realPath);
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public SysFile getFileByCode(String code) {
		SysFile sysFile = new SysFile();
		sysFile.setCode(code);
		sysFile = sysFileMapper.selectOne(sysFile);
		return sysFile;
	}



}
